package com.load.utils;

import java.text.*;
import java.util.*;

import org.joda.time.*;
import org.joda.time.format.*;

public class DateUtil {

	private static final String FORMAT_DATE = "yyyy-MM-dd";

	public static String formatString(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATE);
		return date == null ? "" : sdf.format(date);
	}

	public static Date formatDate(String date) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATE);
		return date == null ? null : sdf.parse(date);
	}

	public static String formatPeriod(String startDate) throws ParseException {
		Date start = formatDate(startDate);
		Date end = new Date();
		Period period = new Period(start.getTime(), end.getTime());

		PeriodFormatter formatter = getFormatter();
		return formatter.print(period);
	}

	public static boolean validateDate(String date) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATE);
			sdf.parse(date);
			return true;
		} catch (ParseException e) {
			e.printStackTrace();
			return false;
		}
	}

	private static PeriodFormatter getFormatter() {
		PeriodFormatterBuilder builder = new PeriodFormatterBuilder();
		builder.appendYears();
		builder.appendSuffix(" year", " years");
		builder.appendSeparator(", ");
		builder.appendMonths();
		builder.appendSuffix(" month", " months");
		builder.appendSeparator(" and ");
		builder.appendDays();
		builder.appendSuffix(" day", " days");

		return builder.toFormatter();
	}

}